import * as server from "@minecraft/server";
import * as data_trading from "./data/trading";
import * as data_entity from "./data/entity";
import * as data_trophy from "./data/trophy";
import * as power_property from "./system/power_property";
import * as derived_tools from "./system/derived_tools";
import * as achieve_plan from "./system/achieve_plan";
import * as query_intel from "./system/query_intel";
import * as math_tools from "./system/math_tools";
import * as interact_component from "./block/interact_component";
import * as destroy_component from "./block/destroy_component";
import * as update_component from "./block/update_component";
import * as place_component from "./block/place_component";
import * as tick_component from "./block/tick_component";
import * as step_component from "./block/step_component";
import * as literature_component from "./item/literature_component";
import * as equipment_component from "./item/equipment_component";
import * as authority_component from "./item/authority_component";
import * as armament_component from "./item/armament_component";
import * as voucher_component from "./item/voucher_component";
import * as tool_component from "./item/tool_component";
import * as prop_component from "./item/prop_component";
import * as entity_subject from "./entity/subject";
import * as attack_component from "./entity/attack_component";
import * as recycling_component from "./entity/recycling_component";
server.world.afterEvents.entitySpawn.subscribe(data => {
    const entity = data.entity;
    const health = entity.getComponent('health');
    if (!entity.isValid())
        return;
    if (!health || health.currentValue <= 10)
        return;
    if (entity.getDynamicProperty('entity:is_initial'))
        return;
    power_property.CreateProperty(entity, data_entity.battle_property.get(entity.typeId));
    entity.setDynamicProperty('entity:create_place', entity.location);
    entity.setDynamicProperty('entity:is_initial', true);
});
server.world.afterEvents.playerSpawn.subscribe(data => {
    const initial = data.initialSpawn;
    const player = data.player;
    if (!initial || player.getDynamicProperty('entity:is_initial'))
        return;
    const anchor = {
        location: math_tools.Vector.floor(player.location),
        dimension: player.dimension.id
    };
    const overworldDimension = server.world.getDimension('minecraft:overworld');
    player.setDynamicProperty('road_sign:出生点', JSON.stringify(anchor));
    power_property.CreateProperty(player, { self_rune: 'rune_void' });
    player.setDynamicProperty('entity:is_initial', true);
    server.system.runTimeout(() => player.addEffect("darkness", 120, { amplifier: 0, showParticles: false }), 240);
    server.system.runTimeout(() => player.onScreenDisplay.setTitle('§4警告! 空间乱流! 警惕<野蜂>!'), 320);
    server.system.runTimeout(() => entity_subject.EnterVacantSpaceWaspTower(player), 360);
    server.system.runTimeout(() => player.playSound('ambient.weather.thunder'), 340);
    server.system.runTimeout(() => player.playSound('ambient.weather.thunder'), 240);
    entity_subject.ReviseWorldRules(overworldDimension);
});
server.world.afterEvents.entityHealthChanged.subscribe(data => {
    const entity = data.entity;
    const value = data.oldValue - data.newValue;
    entity_subject.HealthAlterDisplay(entity, Math.floor(value));
});
server.world.afterEvents.entityHurt.subscribe(data => {
    const target = data.hurtEntity;
    const source = data.damageSource;
    const entity = source.damagingEntity;
    if (!entity || !target || !entity.isValid() || !target.isValid())
        return;
    entity_subject.PlayersLaunchAttacks(target, source, entity);
    entity_subject.EntityUnderAttack(target, source, entity, data.damage);
    entity_subject.PlayersUnderAttack(target, entity);
});
server.world.afterEvents.entityDie.subscribe(data => {
    const target = data.deadEntity;
    const source = data.damageSource;
    const entity = source.damagingEntity;
    if (!entity || !entity.isValid() || !target.isValid() || !target.hasComponent('minecraft:health'))
        return;
    entity_subject.createRewardsAfterDeath(target, entity);
    entity_subject.FunctionsPerformedAfterDeath(target);
});
server.system.afterEvents.scriptEventReceive.subscribe(data => {
    const object = data.sourceEntity;
    const type = data.id.split(/:/);
    if (!object)
        return;
    if (type[0] == 'entity_scripts')
        if (object instanceof server.Player) {
            switch (type[1]) {
                case 'trophy_class':
                    query_intel.Trophy(object, { text: "§9《§u§l §d琉璃§u计划 §9》§r" }, data_trophy.entry);
                    break;
                case 'hailing_trophy':
                    query_intel.Trophy(object, { text: "§9《§u§l 源海百货 §9》§r" }, data_trading.hailing);
                    break;
                case 'intention_class':
                    query_intel.Window(object);
                    break;
                default: break;
            }
        }
        else
            switch (type[1]) {
                case 'role_speak':
                    entity_subject.RoleSpeechAndVoiceManager.Create(object.typeId, 1, { self: object, other: { type: data.message } });
                    break;
                case 'machine_viper_attack':
                    attack_component.MachineViperAttack(object, data.message);
                    break;
                case 'machine_whale_attack':
                    attack_component.MachineWhaleAttack(object, data.message);
                    break;
                case 'machine_wasp_attack':
                    attack_component.MachineWaspAttack(object, data.message);
                    break;
                case 'whale_recycling':
                    recycling_component.WhaleRecycling(object);
                    break;
                case 'python_recycling':
                    recycling_component.PythonRecycling(object);
                    break;
                case 'equip_weapon':
                    entity_subject.EquipWeapon(object);
                    break;
                case 'role_attack':
                    attack_component.RoleLaunchAttack(object, data.message);
                    break;
                case 'constructor':
                    entity_subject.EntityConstruction(object);
                    break;
                case 'contract':
                    entity_subject.CreateContract(object);
                    break;
                case 'tunnel_dragon':
                    entity_subject.TunnelDragonTravel(object, data.message);
                    break;
                case 'unload_inventory_and_destroy':
                    derived_tools.UnloadInventoryAndDestroy(object);
                    break;
                default: break;
            }
    ;
});
server.world.afterEvents.entityHitBlock.subscribe(data => {
    const player = data.damagingEntity;
    if (!(player instanceof server.Player))
        return;
    const item = player.getComponent('inventory')?.container?.getItem(player.selectedSlotIndex);
    const block = data.hitBlock;
    const container = player.getComponent('minecraft:inventory')?.container;
    const token = achieve_plan.ControlEventTrigger.EntityToken;
    if (container)
        switch (item?.typeId) {
            case 'item_authority:material_sorting':
                if (token('物资整理', player, 20))
                    authority_component.ContainerSorting(player, block);
                break;
            case 'item_authority:obtain_block':
                if (token('获取方块', player, 5))
                    prop_component.ObtainBlock(player, container, block);
                break;
            case 'item_tool:magic_crystal_hammer':
                if (token('魔晶锤子', player, 20))
                    tool_component.MagicCrystalHammer(player, item, container, block);
                break;
            case 'item_tool:magic_crystal_key':
                if (token('魔晶钥匙', player, 20))
                    tool_component.MagicCrystalKey(player, item, container, block);
                break;
            case 'item_literature:magic_handbook':
                if (token('魔导手册', player, 20))
                    literature_component.MagicHandbook(player, item, block);
                break;
            default: break;
        }
});
server.world.beforeEvents.worldInitialize.subscribe(data => {
    const custom_component = new Map([
        ['THE_OTHER_SHORE:place.UnrealSpace', place_component.UnrealSpaceTrigger()],
        ['THE_OTHER_SHORE:place.MagicCable', place_component.MagicCableTrigger()],
        ['THE_OTHER_SHORE:place.JungleWoodChair', place_component.JungleWoodChairTrigger()],
        ['THE_OTHER_SHORE:destroy.CrystalTank', destroy_component.CrystalTankTrigger()],
        ['THE_OTHER_SHORE:step.RegionDisplay', step_component.RegionDisplayTrigger()],
        ['THE_OTHER_SHORE:step.VectorEjection', step_component.VectorEjectionTrigger()],
        ['THE_OTHER_SHORE:tick.NihilitySpace', tick_component.NihilitySpaceTrigger()],
        ['THE_OTHER_SHORE:tick.UnrealSpace', tick_component.UnrealSpaceTrigger()],
        ['THE_OTHER_SHORE:tick.BasicPipeline', tick_component.BasicPipelineTrigger()],
        ['THE_OTHER_SHORE:tick.Pulselatch', tick_component.PulselatchTrigger()],
        ['THE_OTHER_SHORE:tick.SuperOmphalos', tick_component.SuperOmphalosTrigger()],
        ['THE_OTHER_SHORE:tick.SuperPulse', tick_component.SuperPulseTrigger()],
        ['THE_OTHER_SHORE:tick.EnableControl', tick_component.EnableControlTrigger()],
        ['THE_OTHER_SHORE:tick.RedstoneDetection', tick_component.RedstoneDetectionTrigger()],
        ['THE_OTHER_SHORE:tick.CountingModule', tick_component.CountingModuleTrigger()],
        ['THE_OTHER_SHORE:tick.ControlPanel', tick_component.ControlPanelTrigger()],
        ['THE_OTHER_SHORE:tick.LogicInverter', tick_component.LogicInverterTrigger()],
        ['THE_OTHER_SHORE:tick.ExclusiveOr', tick_component.ExclusiveOrTrigger()],
        ['THE_OTHER_SHORE:tick.ExclusiveAnd', tick_component.ExclusiveAndTrigger()],
        ['THE_OTHER_SHORE:tick.SignalCompilation', tick_component.SignalCompilationTrigger()],
        ['THE_OTHER_SHORE:tick.SignalFiltering', tick_component.SignalFilteringTrigger()],
        ['THE_OTHER_SHORE:tick.SignalConversion', tick_component.SignalConversionTrigger()],
        ['THE_OTHER_SHORE:tick.CablePort', tick_component.CablePortTrigger()],
        ['THE_OTHER_SHORE:tick.Transmission', tick_component.PackageDeliveryTrigger()],
        ['THE_OTHER_SHORE:tick.Placement', tick_component.PlacementTrigger()],
        ['THE_OTHER_SHORE:tick.Collection', tick_component.CollectionTrigger()],
        ['THE_OTHER_SHORE:tick.Susceptor', tick_component.SusceptorTrigger()],
        ['THE_OTHER_SHORE:tick.Traction', tick_component.TractionTrigger()],
        ['THE_OTHER_SHORE:tick.Omphalos', tick_component.OmphalosTrigger()],
        ['THE_OTHER_SHORE:tick.PlaneGate', tick_component.PlaneGateTrigger()],
        ['THE_OTHER_SHORE:tick.VerticalGate', tick_component.VerticalGateTrigger()],
        ['THE_OTHER_SHORE:tick.PortalAbove', tick_component.PortalAboveTrigger()],
        ['THE_OTHER_SHORE:tick.PortalBelow', tick_component.PortalBelowTrigger()],
        ['THE_OTHER_SHORE:tick.DioriteTable', tick_component.DioriteTableTrigger()],
        ['THE_OTHER_SHORE:tick.JungleWoodChair', tick_component.JungleWoodChairTrigger()],
        ['THE_OTHER_SHORE:tick.StoneMachine', tick_component.StoneMachineTrigger()],
        ['THE_OTHER_SHORE:tick.MetalFormingPress', tick_component.MetalFormingPressTrigger()],
        ['THE_OTHER_SHORE:tick.DestroyTheCore', tick_component.DestroyTheCoreTrigger()],
        ['THE_OTHER_SHORE:tick.MineralMachine', tick_component.MineralMachineTrigger()],
        ['THE_OTHER_SHORE:tick.EnergySupply', tick_component.EnergySupplyTrigger()],
        ['THE_OTHER_SHORE:tick.WindPower', tick_component.WindPowerTrigger()],
        ['THE_OTHER_SHORE:tick.CrystalTank', tick_component.CrystalTankTrigger()],
        ['THE_OTHER_SHORE:tick.TransformTank', tick_component.TransformTankTrigger()],
        ['THE_OTHER_SHORE:tick.AllocationPower', tick_component.AllocationPowerTrigger()],
        ['THE_OTHER_SHORE:tick.MagmaPower', tick_component.MagmaPowerTrigger()],
        ['THE_OTHER_SHORE:tick.WaterPower', tick_component.WaterPowerTrigger()],
        ['THE_OTHER_SHORE:tick.PlantingAndLoggingPower', tick_component.PlantingAndLoggingTrigger()],
        ['THE_OTHER_SHORE:tick.CropDetectionPower', tick_component.CropDetectionTrigger()],
        ['THE_OTHER_SHORE:tick.MagicCrystalLamp', tick_component.MagicCrystalLampTrigger()],
        ['THE_OTHER_SHORE:tick.WindAndRain', tick_component.WindAndRainTrigger()],
        ['THE_OTHER_SHORE:tick.PulsePeakCannon', tick_component.PulsePeakCannonTrigger()],
        ['THE_OTHER_SHORE:tick.Furnace', tick_component.FurnaceTrigger()],
        ['THE_OTHER_SHORE:tick.EnergyExpend', tick_component.EnergyExpendTrigger()],
        ['THE_OTHER_SHORE:tick.RoutineLogisticsReceiver', tick_component.RoutineLogisticsReceiverTrigger()],
        ['THE_OTHER_SHORE:tick.RoutineLogisticsSender', tick_component.RoutineLogisticsSenderTrigger()],
        ['THE_OTHER_SHORE:tick.SurpassLogisticsReceiver', tick_component.SurpassLogisticsReceiverTrigger()],
        ['THE_OTHER_SHORE:tick.SurpassLogisticsSender', tick_component.SurpassLogisticsSenderTrigger()],
        ['THE_OTHER_SHORE:interact.CountingModule', interact_component.CountingModuleTrigger()],
        ['THE_OTHER_SHORE:interact.ControlPanel', interact_component.controlPanelTrigger()],
        ['THE_OTHER_SHORE:interact.LogicInverter', interact_component.LogicInverterTrigger()],
        ['THE_OTHER_SHORE:interact.SignalFiltering', interact_component.signalFilteringTrigger()],
        ['THE_OTHER_SHORE:interact.PackageDelivery', interact_component.PackageDeliveryTrigger()],
        ['THE_OTHER_SHORE:interact.Collection', interact_component.CollectionTrigger()],
        ['THE_OTHER_SHORE:interact.Parameter', interact_component.ParameterTrigger()],
        ['THE_OTHER_SHORE:interact.Susceptor', interact_component.SusceptorTrigger()],
        ['THE_OTHER_SHORE:interact.PlaneGate', interact_component.PlaneGateTrigger()],
        ['THE_OTHER_SHORE:interact.VerticalGate', interact_component.VerticalGateTrigger()],
        ['THE_OTHER_SHORE:interact.PortalAbove', interact_component.PortalAboveTrigger()],
        ['THE_OTHER_SHORE:interact.PortalBelow', interact_component.PortalBelowTrigger()],
        ['THE_OTHER_SHORE:interact.SpecialAlloyPot', interact_component.SpecialAlloyPotTrigger()],
        ['THE_OTHER_SHORE:interact.MetalCamouflage', interact_component.MetalCamouflageTrigger()],
        ['THE_OTHER_SHORE:interact.WoodCamouflage', interact_component.WoodCamouflageTrigger()],
        ['THE_OTHER_SHORE:interact.StoneCamouflage', interact_component.StoneCamouflageTrigger()],
        ['THE_OTHER_SHORE:interact.MagmaPower', interact_component.MagmaPowerTrigger()],
        ['THE_OTHER_SHORE:interact.CrystalTank', interact_component.CrystalTankTrigger()],
        ['THE_OTHER_SHORE:interact.RegionDisplay', interact_component.RegionDisplayTrigger()],
        ['THE_OTHER_SHORE:interact.RoadSignPresets', interact_component.RoadSignPresetsTrigger()],
        ['THE_OTHER_SHORE:interact.Furnace', interact_component.FurnaceTrigger()],
        ['THE_OTHER_SHORE:interact.StorageTank', interact_component.StorageTankTrigger()],
        ['THE_OTHER_SHORE:interact.EnchantmentDissociation', interact_component.EnchantmentDissociationTrigger()],
        ['THE_OTHER_SHORE:interact.StarEnergyInfusion', interact_component.StarEnergyInfusionTrigger()],
    ]);
    const customs = [...custom_component.values()];
    const names = [...custom_component.keys()];
    for (let index = 0; index < customs.length; index++)
        data.blockComponentRegistry.registerCustomComponent(names[index], customs[index]);
});
server.world.beforeEvents.worldInitialize.subscribe(data => {
    const custom_component = new Map([
        ['THE_OTHER_SHORE:item.magic_crystal_screwdriver', tool_component.MagicCrystalScrewdriverTrigger()],
        ['THE_OTHER_SHORE:item.magic_crystal_marbles', tool_component.MagicCrystalMarblesTrigger()],
        ['THE_OTHER_SHORE:item.magic_crystal_wrench', tool_component.MagicCrystalWrenchTrigger()],
        ['THE_OTHER_SHORE:item.magic_crystal_hoe', tool_component.MagicCrystalHoeTrigger()],
        ['THE_OTHER_SHORE:item.magic_crystal_bow', tool_component.MagicCrystalBowTrigger()],
        ['THE_OTHER_SHORE:item.forestry_guidelines', literature_component.ForestryGuidelinesTrigger()],
        ['THE_OTHER_SHORE:item.mineral_dictionary', literature_component.MineralDictionaryTrigger()],
        ['THE_OTHER_SHORE:item.introduction_magic', literature_component.IntroductionMagicTrigger()],
        ['THE_OTHER_SHORE:item.space_transition', literature_component.SpaceTransitionTrigger()],
        ['THE_OTHER_SHORE:item.faerie_contract', literature_component.FaerieContractTrigger()],
        ['THE_OTHER_SHORE:item.faerie_healing', literature_component.FaerieHealingTrigger()],
        ['THE_OTHER_SHORE:item.source_energy', literature_component.SourceEnergyTrigger()],
        ['THE_OTHER_SHORE:item.nihility_space_block', authority_component.NihilitySpaceBlockTrigger()],
        ['THE_OTHER_SHORE:item.stateful_inspection', authority_component.StatefulInspectionTrigger()],
        ['THE_OTHER_SHORE:item.purple_gold_gourd', authority_component.PurpleGoldGourdTrigger()],
        ['THE_OTHER_SHORE:item.material_sorting', authority_component.MaterialSortingTrigger()],
        ['THE_OTHER_SHORE:item.creative_tools', authority_component.CreativeToolsTrigger()],
        ['THE_OTHER_SHORE:item.inhibit_water', authority_component.InhibitWaterTrigger()],
        ['THE_OTHER_SHORE:item.world_of_box', authority_component.WorldOfBoxTrigger()],
        ['THE_OTHER_SHORE:item.dynamic_anchor_point', prop_component.DynamicAnchorPointTrigger()],
        ['THE_OTHER_SHORE:item.mechanized_operation', prop_component.MechanizedOperationTrigger()],
        ['THE_OTHER_SHORE:item.phantom_dispel_dust', prop_component.PhantomDispelDustTrigger()],
        ['THE_OTHER_SHORE:item.reduction_pureness', prop_component.ReductionPurenessTrigger()],
        ['THE_OTHER_SHORE:item.clothing_container', prop_component.ClothingContainerTrigger()],
        ['THE_OTHER_SHORE:item.moment_repair_dew', prop_component.MomentRepairDewTrigger()],
        ['THE_OTHER_SHORE:item.enlightenment', prop_component.EnlightenentTrigger()],
        ['THE_OTHER_SHORE:item.call_tunnel_dragon_guide', armament_component.CallTunnelDragonGuideTrigger()],
        ['THE_OTHER_SHORE:item.call_python_sentinel', armament_component.CallPythonSentinelTrigger()],
        ['THE_OTHER_SHORE:item.call_python_pioneer', armament_component.CallPythonPioneerTrigger()],
        ['THE_OTHER_SHORE:item.call_whale_support', armament_component.CallWhaleSupportTrigger()],
        ['THE_OTHER_SHORE:item.chorus_picture', voucher_component.ChorusPictureTrigger()],
        ['THE_OTHER_SHORE:item.moon_and_stars', voucher_component.MoonAndStarsTrigger()],
        ['THE_OTHER_SHORE:item.flowing_star', voucher_component.FlowingStarTrigger()],
    ]);
    const customs = [...custom_component.values()];
    const names = [...custom_component.keys()];
    for (let index = 0; index < customs.length; index++)
        data.itemComponentRegistry.registerCustomComponent(names[index], customs[index]);
});
server.world.afterEvents.worldInitialize.subscribe(() => {
    equipment_component.EnchantedEquipmentTrigger.BriefCreate('世界初始化容器');
    achieve_plan.ControlEventTrigger.BriefCreate('世界初始化容器');
    achieve_plan.RuneClingEntity.BriefCreate('世界初始化容器');
});
server.world.afterEvents.weatherChange.subscribe(() => {
    entity_subject.GenerateOnSchedule('entity_machine:wasp_guide', 30, { text: '§c§l< 野蜂领航者 袭击 > !!!§r' }, 'portal.trigger');
    entity_subject.GenerateOnSchedule('entity_adrift:windnews', 5, { text: '矿石商人-风信 出现了' }, 'portal.trigger');
});
server.world.afterEvents.playerBreakBlock.subscribe(data => update_component.BlockUpdateAfterEvent(data.block));
server.world.afterEvents.playerPlaceBlock.subscribe(data => update_component.BlockUpdateAfterEvent(data.block));
server.world.beforeEvents.playerBreakBlock.subscribe(data => {
    const block = data.block;
    const item = data.itemStack;
    if (item?.typeId == 'minecraft:structure_void' && item.typeId !== block.typeId)
        data.cancel = true;
});
server.world.afterEvents.playerBreakBlock.subscribe(data => {
    const player = data.player;
    const type = player.getDynamicProperty('block_chain:type');
    if (type && achieve_plan.ControlEventTrigger.EntityToken('区块连锁', player, 20))
        entity_subject.BlockChainEvent(data, type);
});
